package com.gpagers.kit.lucene;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.gpagers.kit.lucene.util.ResultEntity;
import com.gpagers.tools.GlobalConfigHolder;

public class SearchFiles {

	private Analyzer analyzer;
	private Logger logger;
	
	public SearchFiles() {
		analyzer = new IKAnalyzer();
		logger = LoggerFactory.getLogger(SearchFiles.class);
	}

	/**
	 * 自动使用sys.properties配置的索引文件目录indexPath<br>
	 * 检索字段：
	 * String[] fields = { "name", "content" ,"size", "path"};<br>
	 * @param key
	 */
	public List<ResultEntity> searchFile(String key,FieldType... fields) throws Exception {
		IndexReader reader = null;
		IndexSearcher search = null;
		Directory directory = null;
		List<ResultEntity> re_list = new ArrayList< ResultEntity >();
		try {
			String indexPath = GlobalConfigHolder.getProperty("indexPath");
			directory = FSDirectory.open(new File(indexPath));

			reader = DirectoryReader.open(directory);
			search = new IndexSearcher(reader);
			QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_47, 
					FieldType.tramsformToStr(fields), analyzer);
			Query query = parser.parse(key);
			
			//排序根据需要
			//Sort sort = new Sort(field)

			TopDocs topDocs = search.search(query, 100);
			ScoreDoc[] hits = topDocs.scoreDocs;
			logger.debug("搜索'"+key+"'完成...");
			// 关键字高亮显示
			Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
			Scorer scorer = new QueryScorer(query);
			Highlighter highlighter = new Highlighter(formatter, scorer);
			highlighter.setTextFragmenter(new SimpleFragmenter(50));
			for (ScoreDoc doc : hits) {
				Document document = search.doc(doc.doc);
				ResultEntity re = new ResultEntity();
				String name = document.get("name");
				String content = document.get("content");
				String name_ = highlighter.getBestFragment(analyzer, "name", name);
				String content_ = highlighter.getBestFragment(analyzer, "content", content);
				if ("".equals(name_) || name_ == null) {
					name_ = name;
				}
				if ("".equals(content_) || content_ == null) {
					content_ = content;
				}
				re.setContent(content_);
				re.setPath(document.get("path"));
				re.setSize(document.get("size"));
				re.setName(name_);
				re_list.add(re);
			}
		} catch (Exception e) {
			logger.error("搜索文件失败");
			logger.error(e.toString());
			throw e;
		}
		return re_list;
	}
}
